package vip.george.p0206;

public class P206 {

    public class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    /**
     * 新建一个链表，遍历原链表，将原链表节点的值赋给新增节点，并使用头插法进行插入
     * @param head
     * @return
     */
    public ListNode reverseList(ListNode head) {
        ListNode list = null;
        ListNode point = head;
        while (point != null) {
            ListNode newNode = new ListNode(point.val);
            newNode.next = list;
            point = point.next;
            list = newNode;
        }
        return list;
    }

    /**
     * 迭代法
     * @param head
     * @return
     */
    public ListNode reverseList2(ListNode head) {
        ListNode pre = null; //始终指向cur的前一个节点
        ListNode cur = head;
        while (cur != null) {
            ListNode next = cur.next; //暂存当前节点的下一个节点
            // 当前节点指向的内容反转（改为指向前一个）
            cur.next = pre;
            // 移动指针
            pre = cur;
            cur = next;
        }
        return pre;
    }

    /**
     * 递归法
     */
    public ListNode reverseList3(ListNode head) {
        //在本递归方法中，只需要考虑当前节点head，以及当前节点的下一个节点（需要将下一个节点的next指向当前）
        if (head == null || head.next == null) {
            return head;
        }
        ListNode newHead = reverseList3(head.next);
        head.next.next = head; //将本节点后一个节点的next指向本节点
        head.next = null; // 断开本节点和下一个节点的连接
        return newHead;
    }


    public static void main(String[] args) {
        P206 p206 = new P206();
        ListNode node1 = p206.new ListNode(1);
        ListNode node2 = p206.new ListNode(2);
        ListNode node3 = p206.new ListNode(3);
        ListNode node4 = p206.new ListNode(4);
        ListNode node5 = p206.new ListNode(5);
        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        node4.next = node5;
        ListNode result = p206.reverseList3(node1);
        while (result != null) {
            System.out.println(result.val);
            result = result.next;
        }
        System.out.println();
    }

}
